/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2018 TenxCloud. All Rights Reserved.
 * 2018-06-13  @author lizhen
 */

package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/golang/glog"
	"modules.tenxcloud.com/common/utility"
	"modules.tenxcloud.com/common/utility/errors"
)

const (
	ClusterClientKey = "cluster-client"
)

func ClusterClient(c *gin.Context) {
	ci, exist := c.Get(ClusterInfoKey)
	if !exist {
		glog.Fatalf("ClusterClient middleware should work together with ClusterInfo middleware")
	}
	cm := ci.(clusterInfo)
	client, err := utility.NewClientSet(cm)
	if err != nil {
		glog.Errorf("create k8s client set failed, %s", err)
		c.AbortWithStatusJSON(errors.InternalServerError(err))
		return
	}
	c.Set(ClusterClientKey, client)
	c.Next()
}

type clusterInfo interface {
	GetID() string
	GetHost() string
	GetToken() string
}
